package com.monitor.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.monitor.dao.AlbumDao;
import com.monitor.po.Album;
import com.monitor.util.Pager;

@SuppressWarnings("unchecked")
public class AlbumDaoImpl implements AlbumDao {
	private SessionFactory sessionFactory;

	@Override
	public Pager<Album> getAlbumByUid(long uid, int pageSize, int currentPage) throws Exception {
		try {
			Session sesion = this.sessionFactory.getCurrentSession();
			Query query = sesion.createQuery("select count(*) from Album a where a.ownerUid=:ownerUid").setLong("ownerUid", uid);
			int totalCount = ((Number) query.uniqueResult()).intValue();
			int pageCount = (totalCount % pageSize == 0) ? totalCount / pageSize : (totalCount / pageSize) + 1;

			List<Album> list = sesion.createQuery("from Album a where a.ownerUid=:ownerUid order by a.id desc").setLong("ownerUid", uid)
					.setFirstResult((currentPage - 1) * pageSize).setMaxResults(pageSize).list();
			Pager<Album> pager = new Pager<Album>(list, currentPage, totalCount, pageCount);
			return pager;
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting getAlbumByUid()....");
		}
	}

	@Override
	public void saveAlbum(Album album) throws Exception {
		try {
			sessionFactory.getCurrentSession().persist(album);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting saveAlbum()....");
		}
	}

	@Override
	public int deleteAlbumByUid(long uid) throws Exception {
		try {
			return sessionFactory.getCurrentSession().createQuery("delete from Album a  where a.ownerUid=:ownerUid")
					.setLong("ownerUid", uid).executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting deleteAlbumByUid()....");
		}
	}

	@Override
	public void deleteAlbum(Album album) throws Exception {
		try {
			sessionFactory.getCurrentSession().delete(album);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting deleteAlbum()....");
		}
	}

	@Override
	public Album getAlbumById(long id) throws Exception {
		try {
			return (Album) sessionFactory.getCurrentSession().get(Album.class,id);
		} catch (Exception e) {
			e.printStackTrace();
			throw new Exception("exception occured when excuting getAlbumById()....");
		}
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
